<!DOCTYPE html>
<html lang='en'>

<head>
    <meta charset='UTF-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <title>Document</title>
    <script src='../vue.global.js'></script>
</head>

<body>
    <div id="app">
        <p>
            Ask a yes/no question:
            <input v-model="question" />
        </p>
        <hr>
        <p>{{ question }}:{{questionLength}}</p>
        <p>{{ answer }}</p>
        <button @click="getAnswer">getAnswer</button>
    </div>
    <!-- 因为 AJAX 库和通用工具的生态已经相当丰富，Vue 核心代码没有重复 -->
    <!-- 提供这些功能以保持精简。这也可以让你自由选择自己更熟悉的工具。 -->
    <!-- <script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script> -->
    <!-- <script src="./axios.min.js"></script> -->

    <script>
        Vue.createApp({
            data() {
                return {
                    question: "龙哥是聋吗",
                    answer: "五母鸡..."
                }
            },
            methods: {
                getAnswer() {
                    console.log("getAnswer...");
                    this.answer = "容老夫想想..."

                    // 发起网络请求
                    // fetch('https://yesno.wtf/api')
                    //     .then(response => response.json())
                    //     .then(data => {
                    //         this.answer = data.answer
                    //         console.log("then", this.answer);
                    //     })
                    //     .catch(error => {
                    //         this.answer = 'Error! Could not reach the API. ' + error
                    //         console.log("catch", this.answer);
                    //     })

                    setTimeout(() => {
                        this.answer = (Math.random()>.5?"YES":"NO")
                    }, 3000);
                }
            },
            
            computed: {
                questionLength() {
                    return this.question.length
                }
            },

            watch: {
                /* 监听question的变化 */
                question(newValue, oldValue) {
                    console.log("question发生了变化:newValue,oldValue", newValue, oldValue);

                    /* 后续逻辑：只要发现问题以问好结尾 就立即求解 */
                    if (this.question.endsWith("?")) {
                        this.getAnswer()
                    }
                }
            }
        }).mount("#app")
    </script>
</body>

</html>